<?php

namespace App\Model;

use App\Http\Controllers\Constant\Constant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class OABaseModel extends Model
{
    //全局调用
    public function scopeStatus($query, $status = 0)
    {
        if ($status) {
            if($status == OAShenPiLog::SHENPI_STATUS_PASS){
                return $query->where("roleid","<>",roleid());
            }else{
                return $query->where('status', $status);
            }

        } else {
            return $query->whereIn('roleid', OAPositionMapping::getPositionMapping(roleid()));
        }
    }

    public function scopeRoles($query)
    {
        return $query->when(!in_array(roleid(), Constant::ROLE_SUPPER_ADMIN), function ($q) {
            return $q->whereJsonContains('approver', sprintf('%s',strval(admin_id())))
                ->whereJsonContains('role_list', sprintf('%s',strval(roleid())))
                ->when(isPM(), function ($q2) {
                    return $q2->where('deptid', admin("dept_id"));
                });
        });
    }

    /**
     * 批量更新（原生 SQL）
     *
     * @param string $table 表名
     * @param array $data   需要更新的数据 [ [id => 1, col1 => val1], [id => 2, col1 => val2] ]
     * @param string $primaryKey 主键字段，默认 id
     * @return int
     */
    public static function batchUpdate(string $table, array $data, string $primaryKey = 'id'): int
    {
        if (empty($data)) {
            return 0;
        }

        // 提取需要更新的字段（去掉主键）
        $columns = array_keys($data[0]);
        $columns = array_filter($columns, fn($col) => $col !== $primaryKey);

        $ids = array_column($data, $primaryKey);

        $sql = "UPDATE {$table} SET ";
        $bindings = [];

        foreach ($columns as $column) {
            $sql .= "{$column} = CASE ";

            foreach ($data as $row) {
                $value = $row[$column];

                // JSON 自动转换
                if (self::isJsonString($value)) {
                    $decoded = json_decode($value, true);
                    $jsonValue = json_encode($decoded, JSON_UNESCAPED_UNICODE);

                    $sql .= "WHEN {$primaryKey} = ? THEN CAST(? AS JSON) ";
                    $bindings[] = $row[$primaryKey];
                    $bindings[] = $jsonValue;
                } else {
                    $sql .= "WHEN {$primaryKey} = ? THEN ? ";
                    $bindings[] = $row[$primaryKey];
                    $bindings[] = $value;
                }
            }

            $sql .= "ELSE {$column} END, ";
        }

        $sql = rtrim($sql, ', ');

        // WHERE 条件
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $sql .= " WHERE {$primaryKey} IN ({$placeholders})";

        $bindings = array_merge($bindings, $ids);

        return DB::update($sql, $bindings);
    }
    /**
     * 判断字符串是否是 JSON
     */
    protected static function isJsonString($value): bool
    {
        if (!is_string($value)) return false;
        json_decode($value);
        return json_last_error() === JSON_ERROR_NONE;
    }



}
